#pragma once

#include <QThread>
#include <QMutex>

#include "FCMiddleware_global.h"
#include "Depacker.h"
#include "SerialClient.h"

namespace FCMiddleware
{
    class FCMIDDLEWARE_EXPORT SerialClientThread : public QThread
	{
		Q_OBJECT

	public:
		SerialClientThread(Depacker* depacker, const QString& name, unsigned int baud = 115200, QObject *parent = nullptr);
		~SerialClientThread();

	protected:
		QString _portName;
		unsigned int _portBaud;
		QSerialPort::Parity _parity;
		bool _opened;

		QMutex _runLocker;
		volatile bool _isRunning;
		volatile bool _running;

		SerialClient* _serialClient;
		Depacker* _depacker;

	protected:
		void run() override;
		virtual bool sendPacket();
		virtual bool recvCmd();

	public:
		void setPortName(const QString& portName) { _portName = portName; }
		void setPortBaud(unsigned short portBaud) { _portBaud = portBaud; }
		void setPort(const QString& portName, unsigned int portBaud = 115200, QSerialPort::Parity parity = QSerialPort::NoParity);
		void port(QString& portName, unsigned int& portBaud);

		void startServer();
		void stopServer();
		bool isOpened() const { return _opened; }

	signals:
		void stateChanged(unsigned int state, int err, int extra = 0);
		void cmdReady(void* frame);
	};
}

